<template>
  <div class="box"
       id="cashierForm">
    <div class="content">
      <Row type='flex'
           justify='end'
           style='padding:20px'>
        <Col><Button type="primary"
                @click="add"
                style="width:80px">添加</Button></Col>
      </Row>
      <div>
        <Table stripe
               :height="this.tableHeight"
               class="table-list"
               :loading="loading"
               :columns="columns7"
               :data="data6">
          <template slot-scope="{ row }"
                    slot="cashierType">
            <span>{{['收银台','兑奖台','一体机'][row.cashierType]}}</span>
          </template>
          <template slot-scope="{ row,index }"
                    slot="action">
            <Poptip confirm
                    title="是否与收银点解除绑定？"
                    @on-ok="unbind(row,index)"
                    class="poptip_del">
              <Icon class="iconsys iconjiebang"
                    title="解绑"
                    v-if="row.bindCode" />
            </Poptip>
            <Icon class="iconsys iconedit"
                  title="编辑"
                  @click="uptShow(row,index)" />
            <Poptip confirm
                    title="你确定要删除吗？"
                    @on-popper-show="showpopper"
                    @on-ok="remove(row,index)"
                    class="poptip_del"
                    @on-cancel="cancel">
              <Icon class="iconsys icondel"
                    title="删除"
                    v-if="!row.bindCode" />
            </Poptip>
            <Poptip confirm
                    title="是否与收银点强制解除绑定？"
                    @on-ok="unbindForce(row,index)"
                    class="poptip_del">
              <Icon class="iconsys iconqiangzhijiebang"
                    title="强制解绑"
                    v-if="row.bindCode && row.cashierType !== 1" />
            </Poptip>
          </template>
        </Table>
      </div>
      <div class="content_page">
        <span>共{{totalCount}}条</span>
        <Page :total="totalCount"
              ref="pages"
              @on-change="pageNum"
              :page-size="obj.limit"
              class-name="page"
              :current="obj.offset"
              show-sizer
              @on-page-size-change="selectSize" />
      </div>
    </div>
    <Drawer :title="title"
            :closable="true"
            v-model="value1"
            class="shopDrawer"
            @on-close="closed"
            width="540">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="110"
            class="shopDrawer_form">
        <FormItem label="收银点名称:"
                  prop="name">
          <Input v-model="formValidate.name"
                 :disabled="disabled && !!bindCode"
                 placeholder="最多可输入14字"
                 :maxlength="14"
                 class="box_input"
                 @on-keyup="changeName"></Input>
        </FormItem>
        <FormItem label="收银点设备"
                  prop="city">
          <Select v-model="formValidate.city"
                  :disabled="disabled"
                  placeholder="请选择"
                  class="box_input"
                  @on-change="Select_change">
            <Option value="0">收银台</Option>
            <Option value="1">兑奖台</Option>
            <Option value="2">一体机</Option>
          </Select>
        </FormItem>
        <FormItem label="设备ID:"
                  prop="id"
                  v-if="showID">
          <Input v-model="formValidate.id"
                 placeholder="最多可输入40字"
                 :disabled="disabled && !!bindCode"
                 @on-blur="priceBlur"
                 @on-keyup="changeId"
                 :maxlength="40"
                 class="box_input"></Input>
        </FormItem>
        <!-- <FormItem label="收银点项目配置:" prop="interest" style="width:367px">
                <CheckboxGroup v-model="formValidate.interest" @on-change="Checkbox_change">
                    <Checkbox label="游戏卡销售"></Checkbox>
                    <Checkbox label="财务管理"></Checkbox>
                    <Checkbox label="收银台安装"></Checkbox>
                    <Checkbox label="团购销售"></Checkbox>
                    <Checkbox label="水吧销售"></Checkbox>
                    <Checkbox label="营业项收款"></Checkbox>
                    <Checkbox label="票销售"></Checkbox>
                    <Checkbox label="闸机消费"></Checkbox>
                </CheckboxGroup>
            </FormItem> -->
        <FormItem class="shopDrawer_form_btn">
          <Button @click="handleReset('formValidate')"
                  style="width:72px;">取消</Button>
          <Button type="primary"
                  @click="handleSubmit('formValidate')"
                  :disabled="isDisable"
                  style="width:72px;margin-right:8px;margin-left:20px">确定</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>
<script>
import { getCashierList, getCashierSave, getCashierDelete, updateCashierQuery, shopDetailMessage, unbindCashier, unbindForceCashier } from '@/api/setting'
export default {
  data () {
    return {
      tableHeight: 0,
      title: '',
      obj: {
        merchantId: this.$store.state.user.merchantId,
        shopId: this.$route.query.id,
        limit: 10,
        offset: 1
      },
      showID: true,
      totalCount: null,
      isDisable: false,
      value1: false,
      isDelete: true,
      disabled: false,
      isUnbind: true,
      loading: true,
      cashiertype: '',
      cashierId: '',
      shopCode: '',
      shopName: '',
      columns7: [
        {
          title: ' ',
          width: 70
        },
        {
          title: '收银点名称',
          key: 'cashierName'
        },
        {
          title: '收银点设备',
          slot: 'cashierType',
          align: 'center'
        },
        {
          title: '负责人',
          key: 'creator',
          align: 'center'
        },
        {
          title: '操作',
          width: 200,
          slot: 'action'
        }
      ],
      data6: [
      ],
      formValidate: {
        name: '',
        city: '',
        id: '' // 设备的id
        // strAll: '' // 选中的字符串组
      },
      bindCode: '',
      ruleValidate: {
        name: [
          { required: true, message: '收银点名称不能为空', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择收银点设备', trigger: 'change' }
        ],
        id: [
          { required: true, message: '设备ID不能为空', trigger: 'blur' },
          { required: true, message: '必须是数字和字母组成', trigger: 'blur', pattern: /^([A-Za-z]+[0-9]+[A-Za-z0-9]{0,})|([0-9]+[A-Za-z]+[A-Za-z0-9]{0,})$/ }
        ]
      }
    }
  },
  mounted () {
    this.getList({ offset: 0 })
    this.getshopDetail()
    if (!this.hasPermission('moms:setting:cashier')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    selectSize (size) {
      this.obj.limit = size
      this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.obj.limit })
    },
    // 去空格
    changeName () {
      this.formValidate.name = this.formValidate.name.replace(/\s+/g, '')
    },
    changeId () {
      this.formValidate.id = this.formValidate.id.replace(/\s+/g, '')
      this.formValidate.id = this.formValidate.id.replace(/[^A-Za-z0-9]/g, '')
    },
    Select_change (e) {
      this.cashiertype = e
      if (e === '2') {
        this.showID = true
      } else {
        this.showID = false
      }
    },
    add () {
      this.title = '添加收银点'
      this.formValidate.id = ''
      this.value1 = true
      this.showID = false
      this.disabled = false
      this.isDisable = false
    },
    pageNum (page) {
      this.getList({ offset: (page - 1) * this.obj.limit })
    },
    // 关闭清除效验
    closed () {
      this.value1 = false
      this.formValidate.id = ''
      this.$refs.formValidate.resetFields()
    },
    // 获取门店信息
    getshopDetail () {
      shopDetailMessage({
        'shopId': this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.shopName = res.data.data.shopName
        } else {
          this.$Message.error(res.data.error)
        }
      })
    },
    priceBlur () {
      this.formValidate.id = this.formValidate.id.replace(/[^A-Za-z0-9]/g, '')
    },
    showpopper () {
    },
    handleSubmit (name) { // 保存
      if (this.title === '添加收银点') {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setTimeout(() => {
              getCashierSave({
                'shopId': this.$route.query.id,
                'merchantId': this.$store.state.user.merchantId,
                'cashierName': this.formValidate.name,
                'cashierType': this.cashiertype, // 只能传1或者0
                'bindCode': this.formValidate.id,
                'creator': this.$store.state.user.userName,
                'shopName': this.shopName
              }).then((res) => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.value1 = false
                  this.$refs.formValidate.resetFields()
                  this.$Message.success('新增成功')
                  this.$refs.pages.currentPage = 1
                  this.getList({ offset: 0 })
                } else {
                  this.$Message.error(res.data.error)
                }
              })
            }, 200)
          } else {
          }
        })
      } else {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setTimeout(() => {
              updateCashierQuery({
                'shopId': this.$route.query.id,
                'merchantId': this.$store.state.user.merchantId,
                'cashierName': this.formValidate.name,
                'cashierType': this.formValidate.city,
                'cashierId': this.cashierId,
                'bindCode': this.formValidate.id
              }).then((res) => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.value1 = false
                  this.$refs.formValidate.resetFields()
                  this.$Message.success('修改成功')
                  this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.obj.limit })
                } else {
                  this.$Message.error(res.data.error)
                }
              })
            }, 200)
          } else {
          }
        })
      }
    },
    // 解绑
    unbind (obj, idx) {
      if (this.isUnbind) {
        if (!this.isUnbind) {
          return
        }
        this.isUnbind = false
        setTimeout(() => {
          unbindCashier({
            'shopId': this.$route.query.id,
            'merchantId': this.$store.state.user.merchantId,
            'cashierId': obj.cashierId,
            'cashierType': obj.cashierType
          }).then(res => {
            this.isUnbind = true
            if (res.data.status === 200) {
              this.$Message.success('解绑成功')
              this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.obj.limit })
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    unbindForce (obj, idx) {
      if (this.isUnbind) {
        if (!this.isUnbind) {
          return
        }
        this.isUnbind = false
        setTimeout(() => {
          unbindForceCashier({
            'shopId': this.$route.query.id,
            'merchantId': this.$store.state.user.merchantId,
            'cashierId': obj.cashierId,
            'cashierType': obj.cashierType,
            'shopName': this.shopName,
            'creatorId': this.$store.state.user.userId,
            'creator': this.$store.state.user.userName
          }).then(res => {
            this.isUnbind = true
            if (res.data.status === 200) {
              this.$Message.success('强制解绑成功')
              this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.obj.limit })
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    handleReset (name) {
      this.value1 = false
      this.$refs.formValidate.resetFields()
    },
    // 初始化列表
    getList (obj1) {
      this.loading = true
      this.tableHeight = 0
      getCashierList({ ...this.obj, offset: (this.obj.offset - 1) * 10, ...obj1 }).then((res) => {
        if (res.data.status === 200) {
          this.loading = false
          this.totalCount = res.data.totalCount
          this.data6 = res.data.data
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    uptShow (row, index) {
      this.title = '编辑收银点'
      this.disabled = true
      this.isDisable = false
      this.cashierId = row.cashierId
      this.value1 = true
      this.bindCode = row.bindCode
      this.formValidate = {
        name: row.cashierName,
        city: row.cashierType + '',
        id: row.bindCode ? row.bindCode : ''
      }
      if (this.formValidate.city === '2') {
        this.showID = true
      } else {
        this.showID = false
      }
    },
    remove (row, index) { // 确认的回调
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (this.$refs.pages.currentPage !== 1) {
          if (this.totalCount % this.obj.limit === 1) {
            this.$refs.pages.currentPage = this.$refs.pages.currentPage - 1
          }
        }
        setTimeout(() => {
          getCashierDelete({ // 删除接口
            'cashierId': row.cashierId,
            'shopId': this.$route.query.id,
            'merchantId': this.$store.state.user.merchantId
          }).then((res) => {
            this.isDelete = true
            if (res.data.status === 200) {
              this.$Message.success('删除成功')
              getCashierList({ ...this.obj, offset: (this.$refs.pages.currentPage - 1) * this.obj.limit }).then((res) => {
                this.totalCount = res.data.totalCount
                this.data6 = res.data.data
              })
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    cancel () {
    }
  }
}
</script>
<style lang="less" scoped>
.box {
  .content {
    .content_page {
      padding: 20px;
      height: 80px;
      line-height: 80px;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      .page {
        margin-left: 2%;
      }
    }
  }
}
</style>
<style>
.box_input {
  width: 280px;
}
.shopDrawer .shopDrawer_form {
  margin: auto;
  padding-top: 16px;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 16px;
  border-top: 1px solid #e8eaec;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn .ivu-form-item-content {
  text-align: right;
  padding-right: 24px;
}
#cashierForm .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  left: 16px;
  z-index: 100;
}
/* #cashierForm .ivu-poptip-popper {
  top: 0 !important;
} */
</style>
